<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ChatGroup as ChatGroupModel;
use app\common\model\Information as InformationModel;
use app\common\model\ChatRoom as ChatRoomModel;
use app\common\model\User as UserModel;
use app\common\model\ChatGroupContent as ChatGroupContentModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Notice as NoticeModel;
use app\api\controller\Push;
use app\common\model\UserCircle as UserCircleModel;
use think\Config;
use fast\Random;
use think\Db;

class Information extends Api
{
    protected $noNeedLogin = ['releaseNotice','getRedisData','getInformationList'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 信息查询
     * @ApiMethod (POST)
     * @path api/information/getInformationList
     */
    public function getInformationList()
    {
        $list = InformationModel::get_information_list();
        $this->success("请求成功",$list);
    }

    /**
     * 帮助中心
     * @ApiMethod (POST)
     * @path api/information/getHelpCenter
     */
    public function getHelpCenter()
    {
        $where = "id > 0";
        $field = "id,title";
        $order = "weigh DESC,add_time DESC";
        $list = Db::name("help_center")->where($where)->field($field)->order($order)->select();
        $this->success("请求成功",$list);
    }

    /**
     * 帮助详情
     * @ApiMethod (POST)
     * @path api/information/helpCenterInfo
     */
    public function helpCenterInfo()
    {
        $id = $this->request->param("id",'');
        if(!$id){
            $this->error("帮助ID不能为空");
        }
        $where = "id = {$id}";
        $field = "id,content";
        $info =  Db::name("help_center")->where($where)->field($field)->find();
        if($info && !empty($info["content"])){
            $info["content"]=get_image_url($info["content"],protocol_name() . '://' . $_SERVER['SERVER_NAME']);
        }
        $this->success("请求成功",$info);
    }


    /**
     * 消息中心
     * @ApiMethod (POST)
     * @path api/information/chatContentList
     */
    public function chatContentList()
    {
        $user_id = $this->auth->user_id;
        $list = ChatRoomModel::chat_content_list($user_id);
        $this->success("请求成功",$list);
    }

    /**
     * 发起聊天
     * @ApiMethod (POST)
     * @path api/information/createChat
     */
    public function createChat()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $type = $this->request->param("msg_type");
        $msg = $this->request->param("msg");
        if($type == 2 || $type == 3){
            $msg = parse_url($msg)["path"];
        }
//        $msg = "123消息56".date('Y-m-d H:i:s',time());
//        $push = new Push();
//        $array = ["1a0018970babb457b0e","121c83f7612c6222f27"];
//        $push->androidPush($array,$msg);
        $information_id = $this->request->param("information_id",0);
        if(!$user['identification']){
            $identification = Random::alnum(16).'_'.$user_id;
            $user->identification = $identification;
            $user->save();
        }
        if(!$user['access_token']){
            $user_token = ChatRoomModel::getUserToken($user->identification);
            $user->access_token = $user_token['data']['access_token'];
            $user->uuid = $user_token['data']['user']['uuid'];
            $user->save();
        }
        $other_id = $this->request->param("other_id");
        if(!$other_id){
            $this->error("对方用户id不能为空");
        }
        $other_user = UserModel::get($other_id);
        if(!$other_user['identification']){
            $identification = Random::alnum(16).'_'.$other_id;
            $other_user->identification = $identification;
            $other_user->save();
        }
        if(!$other_user['access_token']){
            $user_token = ChatRoomModel::getUserToken($other_user->identification);
            $other_user->access_token = $user_token['data']['access_token'];
            $other_user->uuid = $user_token['data']['user']['uuid'];
            $other_user->save();
        }
        $u_where = "user_id = $user_id";
        $u_where.= " AND to_id = $other_id";
        $u_where.= " AND group_type = '1'";
        if($user_id == $other_id){
            $this->error("自己和自己不能发起聊天");
        }
        $user_room_info = ChatRoomModel::where($u_where)->find();
        if(!$user_room_info){
            $user_room_data = [];
            $user_room_data['user_id'] = $user_id;
            $user_room_data['to_id'] = $other_id;
            $user_room_data['information_id'] = $information_id;
            $user_room_data['group_type'] = 1;
            $user_room_data['type'] = $type;
            $user_room_data['content'] = $msg;
            $user_room_data['last_time'] = time();
            $user_room_data['add_time'] = time();
            $res = ChatRoomModel::create($user_room_data);
            $u_room_id = $res->id;
        }else{
            $u_room_id = $user_room_info->id;
        }
        $o_where = "user_id = $other_id";
        $o_where.= " AND to_id = $user_id";
        $o_where.= " AND group_type = '1'";
        $other_room_info = ChatRoomModel::where($o_where)->find();
        if(!$other_room_info){
            $other_room_data = [];
            $other_room_data['user_id'] = $other_id;
            $other_room_data['to_id'] = $user_id;
            $other_room_data['information_id'] = $information_id;
            $other_room_data['group_type'] = 1;
            $other_room_data['type'] = $type;
            $other_room_data['content'] = $msg;
            $other_room_data['last_time'] = time();
            $other_room_data['add_time'] = time();
            $res = ChatRoomModel::create($other_room_data);
            $o_room_id = $res->id;
        }else{
            $o_room_id = $other_room_info->id;
        }
        $room_ids = $u_room_id.','.$o_room_id;
        $r_where = "((user_id = {$user_id} AND to_id = {$other_id}) OR (user_id = {$other_id} AND to_id = {$user_id})) AND group_type = '1'";
        $room_info = ChatRoomModel::where($r_where)->find();
        if(!$room_info->group_room){
            ChatRoomModel::where($r_where)->update(["group_room"=>$room_ids]);
        }
        $group_data = [];
        $group_data['group_id'] = 0;
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $room_info['group_room'];
        if($type == 2){
            $group_data['content'] = parse_url($msg)["path"];
            $group_data['cover'] = "";
        }elseif ($type == 3){
            $group_data['content'] = parse_url($msg)["path"];
            $thumbnailPath = str_replace('.mp4','.jpg',$msg);
            if (getVideoThumbnail($msg)) {
                $video_cover = $thumbnailPath;
            } else {
                $video_cover = "";
            }
            $group_data['cover'] = splicing_domain($video_cover);
        }else{
            $group_data['content'] = $msg;
            $group_data['cover'] = "";
        }
        $group_data['type'] = $type;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        //增加未读消息数量
        ChatRoomModel::where(["user_id"=>$other_id,"to_id"=>$user_id,"group_type"=>1])->setInc("number",1);
        //消息中心
        $list = ChatRoomModel::chat_content_info($user_id,$other_id,1);
        if($type == 2){
            $msg = '[图片]';
        }
        if($type == 3){
            $msg = '[视频]';
        }
        $list['type'] = $type;
        $list['content'] = str_replace(PHP_EOL,'', $msg);
        $list['last_time'] = getChatTimeStr(time());
        //聊天内容
        $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
        $info["group_room"] = $info["room_ids"];
        $content = [
            "list" => $list,
            "info" => $info,
        ];
        $result = ChatRoomModel::sendToUser($user->identification,$other_user->identification,$content);
        if($result){
            ChatRoomModel::where($r_where)->update(["content"=>$group_data['content'],"last_time"=>time(),"type"=>$type]);
            //$push = new Push();
            //if($other_user->android_registration_id){
            //    $push->androidPush($other_user->android_registration_id,$msg);
            //}
            //if($other_user->ios_registration_id){
            //    $push->androidPush($other_user->ios_registration_id,$msg);
            //}
            $this->success("发送成功",$result);
        }else{
            $this->error("发送失败");
        }
    }

    /**
     * 发帖人主动发一条消息
     * @ApiMethod (POST)
     * @path api/information/circleChat
     */
    public function circleChat($type,$msg,$user_id,$other_id)
    {
        $user = UserModel::where("user_id",$user_id)->find();
        if($type == 2 || $type == 3){
            $msg = parse_url($msg)["path"];
        }
        if(!$user['identification']){
            $identification = Random::alnum(16).'_'.$user_id;
            $user->identification = $identification;
            $user->save();
        }
        if(!$user['access_token']){
            $user_token = ChatRoomModel::getUserToken($user->identification);
            $user->access_token = $user_token['data']['access_token'];
            $user->uuid = $user_token['data']['user']['uuid'];
            $user->save();
        }
        if(!$other_id){
            $this->error("对方用户id不能为空");
        }
        $other_user = UserModel::where("user_id",$other_id)->find();
        if(!$other_user['identification']){
            $identification = Random::alnum(16).'_'.$other_id;
            $other_user->identification = $identification;
            $other_user->save();
        }
        if(!$other_user['access_token']){
            $user_token = ChatRoomModel::getUserToken($other_user->identification);
            $other_user->access_token = $user_token['data']['access_token'];
            $other_user->uuid = $user_token['data']['user']['uuid'];
            $other_user->save();
        }
        if($user_id == $other_id){
            $this->error("自己和自己不能发起聊天");
        }
        $r_where = "((user_id = {$user_id} AND to_id = {$other_id}) OR (user_id = {$other_id} AND to_id = {$user_id})) AND group_type = '1'";
        $room_info = ChatRoomModel::where($r_where)->find();
        $group_data = [];
        $group_data['group_id'] = 0;
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $room_info['group_room'];
        if($type == 2){
            $group_data['content'] = parse_url($msg)["path"];
            $group_data['cover'] = "";
        }elseif ($type == 3){
            $group_data['content'] = parse_url($msg)["path"];
            $thumbnailPath = str_replace('.mp4','.jpg',$msg);
            if (getVideoThumbnail($msg)) {
                $video_cover = $thumbnailPath;
            } else {
                $video_cover = "";
            }
            $group_data['cover'] = splicing_domain($video_cover);
        }else{
            $group_data['content'] = $msg;
            $group_data['cover'] = "";
        }
        $group_data['type'] = $type;
        $group_data['add_time'] = time();
        Db::name("chat_group_content")->insertGetId($group_data);
        $result = ChatRoomModel::sendToUser($user->identification,$other_user->identification,$msg);
        if($result){
            ChatRoomModel::where($r_where)->update(["content"=>$group_data['content'],"last_time"=>time(),"type"=>$type]);
        }else{
            $this->error("发送失败");
        }
    }

    /**
     * 发起群聊
     * @ApiMethod (POST)
     * @path api/information/createGroupChat
     */
    public function createGroupChat()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $type = $this->request->param("msg_type");
        $msg = $this->request->param("msg");

        if($type == 2 || $type == 3){
            $msg = parse_url($msg)["path"];
        }
        if(!$user['identification']){
            $identification = Random::alnum(16).'_'.$user_id;
            $user->identification = $identification;
            $user->save();
        }
        if(!$user['access_token']){
            $user_token = ChatRoomModel::getUserToken($user->identification);
            $user->access_token = $user_token['data']['access_token'];
            $user->uuid = $user_token['data']['user']['uuid'];
            $user->save();
        }
        $group_id = $this->request->param("group_id");
        if(!$group_id){
            $this->error("群聊id不能为空");
        }
        $group_info = ChatGroupModel::get($group_id);
        if(!$group_info){
            $this->error("群聊信息错误");
        }
        $where = "to_id = {$group_id}";
        $where.= " AND information_id = '0'";
        $where.= " AND group_type = '2'";
        $room_id_arr = ChatRoomModel::where($where)->column("id");
        if($room_id_arr){
            $room_id_str = implode(",",$room_id_arr);
        }else{
            $room_id_str = "";
        }
        $room_info = ChatRoomModel::where($where)->find();
        if(!$room_info->group_room){
            ChatRoomModel::where($room_info)->update(["group_room"=>$group_id]);
        }
        $group_data = [];
        $group_data['group_id'] = $group_id;
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $room_id_str;
        if($type == 2){
            $group_data['content'] = parse_url($msg)["path"];
            $group_data['cover'] = "";
        }elseif ($type == 3){
            $group_data['content'] = parse_url($msg)["path"];
            $thumbnailPath = str_replace('.mp4','.jpg',$msg);
            if (getVideoThumbnail($msg)) {
                $video_cover = $thumbnailPath;
            } else {
                $video_cover = "";
            }
            $group_data['cover'] = splicing_domain($video_cover);
        }else{
            $group_data['content'] = $msg;
            $group_data['cover'] = "";
        }
        $group_data['type'] = $type;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        ChatRoomModel::where(["group_room"=>$group_id,"is_margin"=>1,"group_type"=>2])->where("user_id","<>",$user_id)->setInc("number",1);
        //消息中心
        $list = ChatRoomModel::chat_content_info($user_id,$group_id,2);
        $is_margin = ChatRoomModel::where(["group_room"=>$group_id,"is_margin"=>1])->column("user_id");
        if($type == 2){
            $msg = '[图片]';
        }
        if($type == 3){
            $msg = '[视频]';
        }
        $list['is_margin'] = $is_margin;
        $list['type'] = $type;
        $list['content'] = str_replace(PHP_EOL,'', $msg);
        $list['last_time'] = getChatTimeStr(time());
        //聊天内容
        $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
        $info["group_room"] = $group_id;
        $content = [
            "list" => $list,
            "info" => $info,
        ];
        $result = ChatRoomModel::sendToGroup($user->identification,$group_info->h_id,$content);
        // if($info_group['user_ids']){
        //     $user_id_arr = explode(",",$info_group["user_ids"]);
        //     foreach ($user_id_arr as &$value){
        //         $group_user = UserModel::get($value);
        //         $number = ChatRoomModel::where(["user_id"=>$value])->sum("number");
        //         $content = [
        //             "room" => $number,
        //         ];
        //         if($group_user->identification){
        //             ChatRoomModel::sendToUser($group_user->identification,$group_user->identification,$content);
        //         }
        //     }
        // }
        if($result){
            ChatRoomModel::where($where)->update(["content"=>$group_data['content'],"group_room"=>$group_id,"last_time"=>time(),"type"=>$type]);
            /*极光推送*/
            //if($group_info['user_ids']){
            //    $user_id_str = removeValueFromString($group_info["user_ids"],$user_id);
            //    $device_arr = UserModel::where("user_id","IN",$user_id_str)->field("android_registration_id,ios_registration_id")->select();
            //    // 初始化两个新的一维数组
            //    $android_arr = [];
            //    $ios_arr = [];
            //    // 遍历查询结果，将不为空的 android_registration_id 和 ios_registration_id 添加到对应的数组中
            //    foreach ($device_arr as $device) {
            //        if ($device['android_registration_id'] && $device['android_registration_id'] != null) {
            //            $android_arr[] = $device['android_registration_id'];
            //        }
            //        if ($device['ios_registration_id'] && $device['ios_registration_id'] != null) {
            //            $ios_arr[] = $device['ios_registration_id'];
            //        }
            //    }
            //    $push = new Push();
            //    // android推送
            //    if($android_arr){
            //        $push->androidPush($android_arr,$msg);
            //    }
            //    // ios推送
            //    if($ios_arr){
            //        $push->androidPush($android_arr,$msg);
            //    }
            //}
            $this->success("发送成功",$result);
        }else{
            $this->error("发送失败");
        }
    }

    /**
     * 聊天内容
     * @ApiMethod (POST)
     * @path api/information/chatList
     */
    public function chatList()
    {
        $user_id = $this->auth->user_id;
        $msg_id = $this->request->post('msg_id');
        $other_id = $this->request->post('other_id');
        $group_room = $this->request->post('group_room');
        if(!$group_room){
            $this->error("group_room参数不能为空");
        }
        $information_id = $this->request->post('information_id',0);
        if($information_id){
            if($information_id == "P"){
                $group_type = 3;
            }else{
                $group_type = 4;
            }
            $room_info = ChatRoomModel::where(["group_room"=>$group_room,"group_type"=>$group_type,"information_id"=>$information_id])->field("id,to_id,group_type")->find();
        }else{
            $room_info = ChatRoomModel::where(["group_room"=>$group_room])->field("id,to_id,group_type")->find();
        }
        if(!$room_info){
            $this->success("请求成功",[]);
        }
        if($room_info['group_type'] == 2){
            $group_info =  ChatGroupModel::where("id",$room_info['to_id'])->field("user_id,type,jin_userids")->find();
            if($group_info['jin_userids']){
                $jin_id_arr = explode(",",$group_info['jin_userids']);
                if(in_array($user_id,$jin_id_arr)){
                    $is_jin = 1;
                }else{
                    $is_jin = 0;
                }
            }else{
                $is_jin = 0;
            }
            $group_user_id = $group_info['user_id'];
            $group_type = $group_info['type'];
        }else{
            $group_user_id = 0;
            $group_type = $room_info['group_type'];
            $is_jin = 0;
        }
        if($room_info['group_type'] == 2){
            $list = ChatGroupContentModel::get_content_group($msg_id,$room_info['id'],$group_user_id,$group_type,$is_jin,$user_id,$group_room);
        }else{
            $list = ChatGroupContentModel::get_content_list($msg_id,$room_info['id'],$group_user_id,$group_type,$is_jin);
        }
        $this->success("请求成功",$list);
    }

    /**
     * 客服消息
     * @ApiMethod (POST)
     * @path api/information/serviceMessages
     */
    public function serviceMessages()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $information_id = $this->request->param("information_id");
        $group_room = $this->request->param("group_room");
        if(!isset($information_id) || empty($information_id)){
            $this->error("缺少参数information_id");
        }
        if($information_id == "P"){
            $group_type = 3;
        }else{
            $group_type = 4;
        }
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        $where.= " AND is_chao_kf = '1'";
        $identification_arr = UserModel::where($where)->column("identification");
        if(!$identification_arr){
            $this->error("平台没有设置客服");
        }
        $k_where = "is_jin = '0'";
        $k_where.= " AND logout = '0'";
        $k_where.= " AND is_chao_kf = '1'";
        $k_where.= " AND is_xian = '2'";
        $is_xian = UserModel::where($k_where)->count();
        if($is_xian == 0){
            $this->error("暂无客服在线");
        }
        //当前客服不在线时更换客服
        $chat_room_info = ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id,"group_room"=>$group_room])->find();
        if($chat_room_info){
            $user_info = UserModel::where(["user_id"=>$user_id])->field("is_chao_kf,is_xian")->find();
            $to_info = UserModel::where(["user_id"=>$chat_room_info->to_id])->field("is_chao_kf,is_xian")->find();
            if($user_info['is_chao_kf'] == '1' && $to_info['is_chao_kf'] == '1'){
                $this->error("客服不能和客服聊天");
            }
            if($user_info["is_chao_kf"] == '0' && $to_info["is_chao_kf"] == '0'){
                $redis=new \Redis();
                $redis->connect('127.0.0.1',6379);
                $count = count($redis->lrange('identification',0,-1));
                if($count == 0){
                    $this->error("暂无客服在线r");
                }
                $r_info=json_decode($redis->lpop('identification'),true);
                if(!$r_info) {
                    $this->error("队列暂无客服");
                }else {
                    $redis->rPush('identification',json_encode($r_info));
                }
                $other_id = $r_info['user_id'];
                if($chat_room_info['is_kf'] == 1){
                    ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->update(["user_id"=>$other_id]);
                    ChatRoomModel::where(["user_id"=>$chat_room_info['to_id'],"group_type"=>$group_type,"information_id"=>$information_id])->update(["to_id"=>$other_id]);
                }else{
                    ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->update(["to_id"=>$other_id]);
                    ChatRoomModel::where(["user_id"=>$chat_room_info['to_id'],"group_type"=>$group_type,"information_id"=>$information_id])->update(["user_id"=>$other_id]);
                }
            }
            if($chat_room_info['is_kf'] == 0 && $to_info['is_chao_kf'] == '1' && $to_info["is_xian"] == '1'){
                $redis=new \Redis();
                $redis->connect('127.0.0.1',6379);
                $count = count($redis->lrange('identification',0,-1));
                if($count == 0){
                    $this->error("暂无客服在线r");
                }
                $r_info=json_decode($redis->lpop('identification'),true);
                if(!$r_info) {
                    $this->error("队列暂无客服");
                }else {
                    $redis->rPush('identification',json_encode($r_info));
                }
                $other_id = $r_info['user_id'];
                ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->update(["to_id"=>$other_id]);
                ChatRoomModel::where(["user_id"=>$chat_room_info['to_id'],"group_type"=>$group_type,"information_id"=>$information_id])->update(["user_id"=>$other_id]);
            }
        }else{
            $redis=new \Redis();
            $redis->connect('127.0.0.1',6379);
            $count = count($redis->lrange('identification',0,-1));
            if($count == 0){
                $this->error("暂无客服在线!");
            }
        }
        //去除环信没有创建成功的用户
//        $h_user_name = array_filter($identification_arr);
//        $result = ChatRoomModel::getBatchUserStatus($h_user_name);
//        if($result['code'] == 201){
//            $this->error($result["data"]['error_description']);
//        }
//        $arr = $result["data"]["data"];
//        $line = false;
//        foreach ($arr as $v){
//            if(array_shift($v) == "online"){
//                $line = true;
//                break;
//            }
//        }
//        if(!$line){
//            // $this->error("环信暂无客服在线");
//        }
//        $redis=new \Redis();
//        $redis->connect('127.0.0.1',6379);
//        $count = count($redis->lrange('identification',0,-1));
//        if($count == 0){
//            $this->error("暂无客服在线r");
//        }
        // var_dump($redis->lrange('identification',0,-1));die();
        //$number = 0;
        // while ($line){
        //     $r_info=json_decode($redis->lpop('identification'),true);
        //     $number++;
        //     foreach ($arr as $value){
        //         $r_info['identification'] = strtolower($r_info['identification']);
        //         if(isset($value[$r_info['identification']]) && $value[$r_info['identification']] == "online"){
        //             $other_id = $r_info['user_id'];
        //             $line = false;
        //             break;
        //         }
        //     }
        //     $redis->rPush('identification',json_encode($r_info));
        //     if($number > $count){
        //         $line = false;
        //         $this->error("暂无客服在线2");
        //     }
        // }
        $type = $this->request->param("msg_type",1);
        $msg = $this->request->param("msg");
        if($type == 2 || $type == 3){
            $msg = parse_url($msg)["path"];
        }
        $room_info = ChatRoomModel::where(["group_room"=>$group_room,"information_id"=>$information_id])->find();
        $group_data = [];
        $group_data['group_id'] = 0;
        $group_data['user_id'] = $user_id;
        $group_data['room_ids'] = $group_room;
        if($type == 2){
            $group_data['content'] = parse_url($msg)["path"];
            $group_data['cover'] = "";
        }elseif ($type == 3){
            $group_data['content'] = parse_url($msg)["path"];
            $thumbnailPath = str_replace('.mp4','.jpg',$msg);
            if (getVideoThumbnail($msg)) {
                $video_cover = $thumbnailPath;
            } else {
                $video_cover = "";
            }
            $group_data['cover'] = splicing_domain($video_cover);
        }else{
            $group_data['content'] = $msg;
            $group_data['cover'] = "";
        }
        $group_data['type'] = $type;
        $group_data['add_time'] = time();
        $msg_id = Db::name("chat_group_content")->insertGetId($group_data);
        //增加未读消息数量
        ChatRoomModel::where(["to_id"=>$user_id,"group_type"=>$group_type,"group_room"=>$group_room])->where("information_id",$information_id)->setInc("number",1);
        //消息中心
        $list = ChatRoomModel::kf_content_info($group_room,$information_id,$group_type);
        if($type == 2){
            $msg = '[图片]';
        }
        if($type == 3){
            $msg = '[视频]';
        }
        $list['type'] = $type;
        $list['content'] = str_replace(PHP_EOL,'', $msg);
        $list['last_time'] = getChatTimeStr(time());
        //聊天内容
        $info = ChatGroupContentModel::get_content_info($msg_id,$room_info->id);
        $info["group_room"] = $info["room_ids"];
        $info["cover"] = splicing_domain($group_data["cover"]);
        $content = [
            "list" => $list,
            "info" => $info,
        ];
        //$push = new Push();
        if($room_info->user_id == $user_id){
            $otherIdentification = UserModel::where("user_id",$room_info->to_id)->value("identification");
            if(!$otherIdentification){
                $this->error("环信用户错误");
            }
            $result = ChatRoomModel::sendToUser($user->identification,$otherIdentification,$content);
            //$other_info = UserModel::where("user_id",$room_info->to_id)->field("android_registration_id,ios_registration_id")->find();
            //if($other_info->android_registration_id){
            //    $push->androidPush($other_info->android_registration_id,$msg);
            //}
            //if($other_info->ios_registration_id){
            //    $push->androidPush($other_info->ios_registration_id,$msg);
            //}
        }else{
            $otherIdentification = UserModel::where("user_id",$room_info->user_id)->value("identification");
            if(!$otherIdentification){
                $this->error("环信用户错误");
            }
            $result = ChatRoomModel::sendToUser($otherIdentification,$user->identification,$content);
            //$other_info = UserModel::where("user_id",$room_info->user_id)->field("android_registration_id,ios_registration_id")->find();
            //if($other_info->android_registration_id){
            //    $push->androidPush($other_info->android_registration_id,$msg);
            //}
            //if($other_info->ios_registration_id){
            //    $push->androidPush($other_info->ios_registration_id,$msg);
            //}
        }
        if($result){
            ChatRoomModel::where("group_room",$group_room)->update(["content"=>$group_data['content'],"last_time"=>time(),"type"=>$type]);
            $this->success("发送成功",$result);
        }else{
            $this->error("发送失败");
        }
    }

    /*
     * 消息数量
     * @ApiMethod (POST)
     * @path api/information/numberMessages
     * */
    public function numberMessages()
    {
        $user_id = $this->auth->user_id;
        $chat_room_id = $this->request->param("chat_room_id");
        if(!$chat_room_id){
            $this->error("聊天室ID不能为空");
        }
        $char_room_info = ChatRoomModel::where("group_room",$chat_room_id)->find();
        if(!$char_room_info){
            $this->error("聊天室信息错误");
        }
        ChatRoomModel::where(["group_room"=>$chat_room_id,"user_id"=>$user_id])->update(["number"=>0]);
        $this->success("请求成功");
    }

    /*
     * 发公告
     * @ApiMethod (POST)
     * @path api/information/releaseNotice
     * */
    public function releaseNotice()
    {
        $where = "is_jin = '0'";
        $where.= " AND logout = '0'";
        $field = "user_id,username,identification,uuid";
        $notice = ConfigModel::getConfigValue("notice");
        $content = [
            "notice" => $notice,
        ];
        $pageSize = 600; // 每次处理的数据量
        $page = 1; // 初始化页数
        do {
            $users =UserModel::where($where)->field($field)->limit(($page - 1) * $pageSize, $pageSize)->select();
            // 如果查询到数据，则逐条处理
            if (!empty($users)) {
                foreach ($users as &$user) {
                    if($user['identification']){
                        ChatRoomModel::sendToUser('EWx24UyplePq3vR5',$user['identification'],$content);
                    }
                }
            }
            $page++; // 增加页数，准备处理下一页数据
            // 如果查询的数据数量少于$pageSize，说明数据已处理完毕
        } while (count($users) === $pageSize);
        $this->success("请求成功");
    }

    /*
     * 获取消息数
     * @ApiMethod (POST)
     * @path api/information/getNumber
     * */
    public function getNumber()
    {
        $user_id = $this->auth->user_id;
        $where = "user_id = {$user_id}";
        $number = ChatRoomModel::where($where)->sum("number");
        $this->success("请求成功",$number);
    }

    /*
     * 平台消息数
     * @ApiMethod (POST)
     * @path api/information/getNoticeNumber
     * */
    public function getNoticeNumber()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $add_time = $user->add_time;
        $read_notice_arr = Db::name("notice_read")->where("user_id",$user_id)->column("notice_id");
        $number = NoticeModel::where("id","NOT IN",$read_notice_arr)->where("add_time",">=",$add_time)->count();
        $this->success("请求成功",$number);
    }
    
    /*
     * 创建聊天室
     * @ApiMethod (POST)
     * @path api/information/createRoom
     * */
    public function createRoom()
    {
        $user_id = $this->auth->user_id;
        $user = $this->auth->getUser();
        $re_other_id = $this->request->param("other_id");
        $information_id = $this->request->post("information_id");
        $circle_id = $this->request->post("circle_id",0);
        if(!isset($re_other_id)){
            $this->error("缺少参数other_id");
        }
        if(!isset($information_id)){
            $this->error("缺少参数information_id");
        }
        if($information_id == "P"){
            $group_type = 3;
            $room = "P";
        }else{
            $group_type = 4;
            $room = "X";
        }
        if($information_id == "P" || $information_id != 0){
            $k_where = "is_jin = '0'";
            $k_where.= " AND logout = '0'";
            $k_where.= " AND is_chao_kf = '1'";
            $k_where.= " AND is_xian = '2'";
            $is_xian = UserModel::where($k_where)->count();
            if($is_xian == 0){
                $this->error("暂无客服在线");
            }
            $chat_room_info = ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->find();
            if($chat_room_info){
                $user_info = UserModel::where(["user_id"=>$chat_room_info->to_id])->field("is_chao_kf,is_xian")->find();
                if($user_info["is_chao_kf"] == '0'){
                    $redis=new \Redis();
                    $redis->connect('127.0.0.1',6379);
                    $count = count($redis->lrange('identification',0,-1));
                    if($count == 0){
                        $this->error("暂无客服在线r");
                    }
                    $r_info=json_decode($redis->lpop('identification'),true);
                    if(!$r_info) {
                        $this->error("队列暂无客服");
                    }else {
                        $redis->rPush('identification',json_encode($r_info));
                    }
                    $other_id = $r_info['user_id'];
                    ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->update(["to_id"=>$other_id]);
                    ChatRoomModel::where(["user_id"=>$chat_room_info['to_id'],"group_type"=>$group_type,"information_id"=>$information_id])->update(["user_id"=>$other_id]);
                }
                if(($user_info['is_chao_kf'] == '1' && $user_info["is_xian"] == '1')){
                    $redis=new \Redis();
                    $redis->connect('127.0.0.1',6379);
                    $count = count($redis->lrange('identification',0,-1));
                    if($count == 0){
                        $this->error("暂无客服在线r");
                    }
                    $r_info=json_decode($redis->lpop('identification'),true);
                    if(!$r_info) {
                        $this->error("队列暂无客服");
                    }else {
                        $redis->rPush('identification',json_encode($r_info));
                    }
                    $other_id = $r_info['user_id'];
                    ChatRoomModel::where(["user_id"=>$user_id,"group_type"=>$group_type,"information_id"=>$information_id])->update(["to_id"=>$other_id]);
                    ChatRoomModel::where(["user_id"=>$chat_room_info['to_id'],"group_type"=>$group_type,"information_id"=>$information_id])->update(["user_id"=>$other_id]);
                }
                $this->success("创建成功",$chat_room_info->group_room);
            }
            $where = "is_jin = '0'";
            $where.= " AND logout = '0'";
            $where.= " AND is_chao_kf = '1'";
            $identification_arr = UserModel::where($where)->column("identification");
            if(!$identification_arr){
                $this->error("平台没有设置客服");
            }
            //去除环信没有创建成功的用户
            $h_user_name = array_filter($identification_arr);
            $result = ChatRoomModel::getBatchUserStatus($h_user_name);
            if($result['code'] == 201){
                $this->error($result["data"]['error_description']);
            }
            $arr = $result["data"]["data"];
            $line = false;
            foreach ($arr as $v){
                if(array_shift($v) == "online"){
                    $line = true;
                    break;
                }
            }
            if(!$line){
                // $this->error("环信暂无客服在线");
            }
            $redis=new \Redis();
            $redis->connect('127.0.0.1',6379);
            $count = count($redis->lrange('identification',0,-1));
            if($count == 0){
                $this->error("暂无客服在线r");
            }
            // var_dump($redis->lrange('identification',0,-1));die();
            //$number = 0;
            // while ($line){
            //     $r_info=json_decode($redis->lpop('identification'),true);
            //     $number++;
            //     foreach ($arr as $value){
            //         $r_info['identification'] = strtolower($r_info['identification']);
            //         if(isset($value[$r_info['identification']]) && $value[$r_info['identification']] == "online"){
            //             $other_id = $r_info['user_id'];
            //             $line = false;
            //             break;
            //         }
            //     }
            //     $redis->rPush('identification',json_encode($r_info));
            //     if($number > $count){
            //         $line = false;
            //         $this->error("暂无客服在线2");
            //     }
            // }
            $r_info=json_decode($redis->lpop('identification'),true);
            if(!$r_info) {
                $this->error("队列暂无客服");
            }else {
                $redis->rPush('identification',json_encode($r_info));
            }
            $other_id = $r_info['user_id'];
            $type = $this->request->param("msg_type",1);
            $msg = $this->request->param("msg");
            if($type == 2 || $type == 3){
                $msg = parse_url($msg)["path"];
            }
            if(!$user['identification']){
                $identification = Random::alnum(16).'_'.$user_id;
                $user->identification = $identification;
                $user->save();
            }
            if(!$user['access_token']){
                $user_token = ChatRoomModel::getUserToken($user->identification);
                $user->access_token = $user_token['data']['access_token'];
                $user->uuid = $user_token['data']['user']['uuid'];
                $user->save();
            }
            if(!$other_id){
                $this->error("对方用户id不能为空");
            }
            $other_user = UserModel::get($other_id);
            if(!$other_user['identification']){
                $identification = Random::alnum(16).'_'.$other_id;
                $other_user->identification = $identification;
                $other_user->save();
            }
            if(!$other_user['access_token']){
                $user_token = ChatRoomModel::getUserToken($other_user->identification);
                $other_user->access_token = $user_token['data']['access_token'];
                $other_user->uuid = $user_token['data']['user']['uuid'];
                $other_user->save();
            }
            $u_where = "user_id = $user_id";
            $u_where.= " AND to_id = $other_id";
            $u_where.= " AND group_type = $group_type";
            $u_where.= " AND information_id = '{$information_id}'";
            if($user_id == $other_id){
                $this->error("自己和自己不能发起聊天");
            }
            $user_room_info = ChatRoomModel::where($u_where)->find();
            if(!$user_room_info){
                $user_room_data = [];
                $user_room_data['user_id'] = $user_id;
                $user_room_data['to_id'] = $other_id;
                $user_room_data['information_id'] = $information_id;
                $user_room_data['group_type'] = $group_type;
                $user_room_data['type'] = $type;
                $user_room_data['is_kf'] = 0;
                $user_room_data['content'] = $msg;
                $user_room_data['last_time'] = time();
                $user_room_data['add_time'] = time();
                $res = ChatRoomModel::create($user_room_data);
                $u_room_id = $res->id;
            }else{
                $u_room_id = $user_room_info->id;
            }
            $o_where = "user_id = $other_id";
            $o_where.= " AND to_id = $user_id";
            $o_where.= " AND group_type = $group_type";
            $o_where.= " AND information_id = '{$information_id}'";
            $other_room_info = ChatRoomModel::where($o_where)->find();
            if(!$other_room_info){
                $other_room_data = [];
                $other_room_data['user_id'] = $other_id;
                $other_room_data['to_id'] = $user_id;
                $other_room_data['information_id'] = $information_id;
                $other_room_data['group_type'] = $group_type;
                $other_room_data['type'] = $type;
                $other_room_data['is_kf'] = 1;
                $other_room_data['content'] = $msg;
                $other_room_data['last_time'] = time();
                $other_room_data['add_time'] = time();
                $res = ChatRoomModel::create($other_room_data);
                $o_room_id = $res->id;
            }else{
                $o_room_id = $other_room_info->id;
            }
            $room_ids = $u_room_id.','.$o_room_id.','.$room;
            $r_where = "((user_id = {$user_id} AND to_id = {$other_id}) OR (user_id = {$other_id} AND to_id = {$user_id})) AND group_type = {$group_type} AND information_id = '{$information_id}'";
            $room_info = ChatRoomModel::where($r_where)->find();
            if(!$room_info->group_room){
                ChatRoomModel::where($r_where)->update(["group_room"=>$room_ids]);
            }
            $this->success("创建成功",$room_ids);
        }else{
            $group_type = 1;
            $u_where = "user_id = $user_id";
            $u_where.= " AND to_id = $re_other_id";
            $u_where.= " AND group_type = $group_type";
            $user_room_info = ChatRoomModel::where($u_where)->find();
            if(!$user_room_info){
                $user_room_data = [];
                $user_room_data['user_id'] = $user_id;
                $user_room_data['to_id'] = $re_other_id;
                $user_room_data['information_id'] = $information_id;
                $user_room_data['circle_id_str'] = $circle_id;
                $user_room_data['group_type'] = $group_type;
                $user_room_data['type'] = 1;
                $user_room_data['content'] = 0;
                $user_room_data['last_time'] = time();
                $user_room_data['add_time'] = time();
                $res = ChatRoomModel::create($user_room_data);
                $u_room_id = $res->id;
            }else{
                $u_room_id = $user_room_info->id;
            }
            $o_where = "user_id = $re_other_id";
            $o_where.= " AND to_id = $user_id";
            $o_where.= " AND group_type = $group_type";
            $other_room_info = ChatRoomModel::where($o_where)->find();
            if($circle_id){
                $circle_info = UserCircleModel::where("id",$circle_id)->field("user_id,title")->find();
            }else{
                $circle_info['user_id'] = 0;
                $circle_info["title"] = 0;
            }
            if(!$other_room_info){
                $other_room_data = [];
                $other_room_data['user_id'] = $re_other_id;
                $other_room_data['to_id'] = $user_id;
                $other_room_data['information_id'] = $information_id;
                $other_room_data['circle_id_str'] = $circle_id;
                $other_room_data['group_type'] = $group_type;
                $other_room_data['type'] = 1;
                $other_room_data['content'] = "请问是想咨询《".$circle_info["title"]."》吗？";
                $other_room_data['last_time'] = time();
                $other_room_data['add_time'] = time();
                $res = ChatRoomModel::create($other_room_data);
                $o_room_id = $res->id;
            }else{
                $o_room_id = $other_room_info->id;
            }
            $group_room = $u_room_id.','.$o_room_id;
            $r_where = "((user_id = {$user_id} AND to_id = {$re_other_id}) OR (user_id = {$re_other_id} AND to_id = {$user_id})) AND group_type = '1'";
            $room_info = ChatRoomModel::where($r_where)->find();
            if(!$room_info->group_room){
                ChatRoomModel::where($r_where)->update(["group_room"=>$group_room]);
            }
            list($num1, $num2) = orderNumbers($u_room_id, $o_room_id);
            $group_room = $num1 .','.$num2;
            if($circle_id){
                if($circle_id == $room_info['circle_id_str']){
                    $msg = "请问是想咨询《".$circle_info["title"]."》吗？";
                    $this->circleChat(1,$msg,$circle_info['user_id'],$user_id);
                }else{
                    // 将circle_id_str和接收到的值都转换成数组
                    $circle_id_array = explode(',', $room_info['circle_id_str']);
                    $received_values_array = explode(',', $circle_id);
                    // 使用array_merge函数将两个数组合并
                    $merged_circle_ids = array_merge($circle_id_array, $received_values_array);
                    // 使用array_unique函数移除重复的值
                    $filtered_circle_ids = array_unique($merged_circle_ids);
                    // 将最终的数组转换回逗号分隔的字符串
                    $circle_id_str = implode(',', $filtered_circle_ids);
                    ChatRoomModel::where($r_where)->update(["circle_id_str"=>$circle_id_str]); // 存到聊天室
                    if(!in_array($circle_id,$circle_id_array)){
                        $msg = "请问是想咨询《".$circle_info["title"]."》吗？";
                        $this->circleChat(1,$msg,$circle_info['user_id'],$user_id);
                    }
                }
            }
            $this->success("创建成功",$group_room);
        }
    }

    public function getRedisData()
    {
        $redis=new \Redis();
        $redis->connect('127.0.0.1',6379);
        $count = count($redis->lrange('identification',0,-1));
        dump($redis->lrange('identification',0,-1));die();
//        if ($redis->exists($key)) {
//            $redis->del($key);
//            echo "键 '$key' 已被清除。\n";
//        } else {
//            echo "键 '$key' 不存在。\n";
//        }
    }

}
